(:xquery version "1.0";:)

declare namespace exist = "http://exist.sourceforge.net/NS/exist";
declare option exist:serialize "method=html media-type=text/html omit-xml-declaration=yes indent=yes";

declare variable $url external;
declare variable $year external;
declare variable $region external;
declare variable $month external;

declare function local:add-row($data) {
	let $str := concat(
		"["
		, string-join(
			$data
			, ","
		)
		, "]")

	return $str
};

declare function local:create-graph() {

	<div id="weatherGraph">
	<script type="text/javascript" src="http://www.google.com/jsapi">&amp;nbsp;</script>
	<script type="text/javascript">
		google.load('visualization', '1', {{packages: ['corechart']}});
	</script>
	<script type="text/javascript">
		function drawVisualization() {{
			var data = google.visualization.arrayToDataTable([
				{if ($region="")
				 then
				 	'["county","temperature"],'
				 else
				 	'["month","temperature"],'
				}
			{
			let $str := string-join(
				if ($region="")
				then
					for $a in doc($url)/weather/dates/area
						return local:add-row(
							(concat("'",$a/@region,"'")
							,$a/type[@type="t"]/date[@month=$month])
						)
				else
					for $d in doc($url)/weather/dates/area[@region=$region]/type[@type="t"]/date
						return local:add-row(
							(concat('"',$d/@month,'"')
							,$d)
						)
				, ","
				)
			return $str
			}]);

		new google.visualization.ColumnChart(document.getElementById('weatherGraph')).
			draw(data,
				{{title:{$year},
				width:600, height:400,
				vAxis: {{ title: "temperature" }},
				hAxis: {{ title: {
					if ($region="")
					then
						'"counties"'
					else
						'"months"'
					},
					showTextEvery: 1,
					slantedText: true,
					slantedTextAngle: 45
					}}
				}}
			);
		}}
		google.setOnLoadCallback(drawVisualization);
	</script>
	</div>

};

local:create-graph()
